package main

import (
	"gf-mysql-transfer/internal/config/log"
	"gf-mysql-transfer/internal/consts"
	_ "gf-mysql-transfer/internal/packed"
	"gf-mysql-transfer/internal/utility/allyes"
	_ "gf-mysql-transfer/internal/utility/allyes"
	_ "github.com/gogf/gf/contrib/drivers/clickhouse/v2"
	_ "github.com/gogf/gf/contrib/drivers/dm/v2"
	_ "github.com/gogf/gf/contrib/drivers/mssql/v2"
	_ "github.com/gogf/gf/contrib/drivers/mysql/v2"
	_ "github.com/gogf/gf/contrib/drivers/pgsql/v2"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gcfg"
	"github.com/gogf/gf/v2/os/gcmd"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/text/gstr"

	"github.com/gogf/gf/v2/os/gctx"

	"gf-mysql-transfer/internal/cmd"
)

func main() {
	defer func() {
		if exception := recover(); exception != nil {
			if err, ok := exception.(error); ok {
				glog.Print(gctx.New(), err.Error())
			} else {
				panic(exception)
			}
		}
	}()
	var (
		ctx = gctx.New()
	)
	// CLI configuration.
	if path, _ := gfile.Search(consts.CliFolderName); path != "" {
		if adapter, ok := g.Cfg().GetAdapter().(*gcfg.AdapterFile); ok {
			if err := adapter.SetPath(path); err != nil {
				glog.Fatal(ctx, err)
			}
		}
	}

	// zsh alias "git fetch" conflicts checks.
	handleZshAlias()

	// -y option checks.
	allyes.Init()
	log.InitLog()

	command, err := gcmd.NewFromObject(cmd.Transfer)
	if err != nil {
		panic(err)
	}
	err = command.AddObject(
		cmd.Serve,
		cmd.Version,
	)
	if err != nil {
		panic(err)
	}
	command.Run(ctx)
}

// zsh alias "git fetch" conflicts checks.
func handleZshAlias() {
	if home, err := gfile.Home(); err == nil {
		zshPath := gfile.Join(home, ".zshrc")
		if gfile.Exists(zshPath) {
			var (
				aliasCommand = `alias transfer=transfer`
				content      = gfile.GetContents(zshPath)
			)
			if !gstr.Contains(content, aliasCommand) {
				_ = gfile.PutContentsAppend(zshPath, "\n"+aliasCommand+"\n")
			}
		}
	}
}
